//
//  AppDelegate.m
//  华康通
//
//  Created by leiyu on 16/9/12.
//  Copyright © 2016年 com.huakang. All rights reserved.
//

#import "AppDelegate.h"
#import "UIFont+SelfFont.h"
#import "GIFLoadingModel/SVProgressHUD_Extension.h"
#import "GIFLoadingModel/UIImage+GIFImage.h"
#import "Controllers/FirstViewController/FirstTableViewController.h"
#import "Controllers/SecondViewController/SecondViewController.h"
#import "Controllers/ThreeViewController/ThreeViewController.h"
#import "Controllers/FourViewController/FourViewController.h"


//友盟推送必须用到的类文件
#import "UMessage.h"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
#import <UserNotifications/UserNotifications.h>
#endif
//以下几个库仅作为调试引用引用的
#import <AdSupport/AdSupport.h>
#import <CommonCrypto/CommonDigest.h>
#import "UMMobClick/MobClick.h"
#import <AVFoundation/AVFoundation.h>
#import "GGView.h"
#import "JSONFromImages.h"
#import "LLTabBar/LLTabBar.h"


#define ZHENGSHI  @"59ae0e0df29d982248000040"


//////////----------------**************----------------\\\\\\\\\\
//新闻页面  - "news6566556565656" value
#import "NewsIformationDetailController.h"
//产品详情页面   - "product6566556565656_1" value 产品＋产品id＋_是否出售
#import "ProductDetailViewController.h"
//0元赠险   - "nomoney" value
#import "NoMoneyListViewController.h"
//关于我们的视频h5页面(暂时只能跳转到关于我们列表)   - "aboutus" value
#import "AboutUSController.h"
//个人中心  - "first4" value
//分类  - "first2" value
//工具 - "first3" value
//////////----------------**************----------------\\\\\\\\\\


@import ContactsUI;

@interface AppDelegate ()<UNUserNotificationCenterDelegate,UIAlertViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) NSDictionary* userInfo;
//广告图右上角的按钮
@property (nonatomic, strong) UIButton* button;
@property (nonatomic, strong) UIScrollView* scrollView;
@property (nonatomic, strong) NSArray* images;
@property (nonatomic, strong) UIView* backView;
@property (nonatomic, strong) UIImageView* imageView;
@property (nonatomic, strong) GGView* ggView;
//记录广告图的尺寸
@property (nonatomic, unsafe_unretained) CGFloat ratio;

@end

@implementation AppDelegate

- (UIView*)backView
{
    if (!_backView)
    {
        _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, UISCREENHEIGHT)];
        _backView.backgroundColor = FFFFFFColor;
        self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, UISCREENHEIGHT)];
        self.imageView.image = [self getLaunchImage];
        [_backView addSubview:self.imageView];
    }
    return _backView;
}

//获取当前项目启动图的文件名
- (NSString *)getLaunchImageName
{
    NSString *viewOrientation = @"Portrait";
    if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) {
        viewOrientation = @"Landscape";
    }
    NSString *launchImageName = nil;
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    UIWindow *currentWindow = [[UIApplication sharedApplication].windows firstObject];
    CGSize viewSize = currentWindow.bounds.size;
    for (NSDictionary* dict in imagesDict)
    {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            launchImageName = dict[@"UILaunchImageName"];
        }
    }
    return launchImageName;
}

//获取当前项目的启动图
- (UIImage *)getLaunchImage
{
    return LoadImage([self getLaunchImageName]);
}


//加载展示广告图
- (void)showGGImageWithArr:(NSArray*)arr withRatio:(CGFloat)ratio
{
    __weak AppDelegate* weakSelf = self;
    if (arr.count > 0)
    {
        self.ggView = [[GGView alloc]initWithImages:arr withRatio:1/ratio];
        self.ggView.frame = CGRectMake(0, 0, UISCREENWEITH, UISCREENHEIGHT);
        self.ggView.clickBlock = ^(NSInteger tag) {

            NSLog(@"点击了广告图中第%ld张图片",(long)(tag + 1));
            NSArray* urls = [weakSelf getURLSForImagesWithArr:weakSelf.images];
            GGH5WebVC* vc = [[GGH5WebVC alloc]initWithNibName:@"GGH5WebVC" bundle:nil];
            vc.html = urls[tag];
            if (![urls[tag] isEqualToString:@""])
            {
                [weakSelf.backView removeFromSuperview];
                weakSelf.backView = nil;
                [weakSelf.ggView removeFromSuperview];
                weakSelf.ggView = nil;
                //获取当前控制器 跳转
                if ([[weakSelf currentViewController1] isKindOfClass:[UINavigationController class]])
                {
                    UINavigationController* navi = (UINavigationController*)[weakSelf currentViewController1];
                    [navi pushViewController:vc animated:YES];
                }
            }
        };
        [self.window addSubview:self.ggView];
    }

    [self.backView removeFromSuperview];
    self.backView = nil;
}

//网络请求数据
- (void)postGetImages
{
    NSDictionary* json = @{@"platformType":@"1",
                           @"orderType":@"01",
                           @"requestService":@"getHktConfig",
                           @"requestObject":@{
                                   @"imageType": @"ios_1"
                                   }
                           };
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
//    NSLog(@"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&首页获取启动广告图的接口连接url = %@",url);
    [self getPicturesWithURL:url withParam:json];
}

- (void)getPicturesWithURL:(NSString*)url withParam:(NSDictionary*)param
{
    self.ratio = 0.0;
    
    [XHNetworking POST:url parameters:param success:^(NSData *responseObject) {
        id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
//        NSLog(@"首页获取启动广告图+++++++++= = %@",json);
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            if ([json isKindOfClass:[NSDictionary class]] && json)
            {
                if ([json[@"resultCode"] isEqualToString:@"0"])
                {
                    self.ratio = [json[@"responseObject"][@"size"] doubleValue];
                    NSMutableArray* arr = [NSMutableArray array];
                    for (NSDictionary* dic in json[@"responseObject"][@"image"])
                    {
                        JSONFromConfig* images = [JSONFromConfig configWithJSON:dic];
                        [arr addObject:images];
                    }
                    self.images = [arr copy];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //展示广告图
                [self showGGImageWithArr:self.images withRatio:self.ratio];
            });
        });
    } failure:^(NSError *error) {
//        NSLog(@"首页获取启动广告图+++++++++错误提示 = %@",error);
        //展示广告图
        dispatch_async(dispatch_get_main_queue(), ^{
            //展示广告图
            [self showGGImageWithArr:self.images withRatio:self.ratio];
        });
    }];
}

//得到图片进去链接数组
- (NSArray*)getURLSForImagesWithArr:(NSArray*)arr
{
    NSMutableArray* array = [NSMutableArray array];
    for (JSONFromConfig* images in arr)
    {
        [array addObject:images.imageUrlSecond];
    }
    return [array copy];
}

#pragma mark --- SVProgressHUD 偏好设置
- (void)svPreferrenceConf
{
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
    [SVProgressHUD setBackgroundColor:ClEARColor];
    [SVProgressHUD setInfoImage:[UIImage imageWithGIFNamed:@"loading"]];
    UIImageView *svImgView = [[SVProgressHUD sharedView] valueForKey:@"imageView"];
    CGRect imgFrame = svImgView.frame;
    // 设置图片的显示大小
    imgFrame.size = CGSizeMake(40, 40);
    svImgView.frame = imgFrame;
}

- (void)showTabbar
{
    FirstTableViewController* firstVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"FirstVC"];
    UINavigationController* firstNV = [[UINavigationController alloc]initWithRootViewController:firstVC];
    SecondViewController* secondVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"SecondVC"];
    UINavigationController* secondNV = [[UINavigationController alloc]initWithRootViewController:secondVC];
    ThreeViewController* threeVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ThreeVC"];
    UINavigationController* threeNV = [[UINavigationController alloc]initWithRootViewController:threeVC];
    FourViewController* fourVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"FourVC"];
    UINavigationController* fourNV = [[UINavigationController alloc]initWithRootViewController:fourVC];
    UITabBarController *tabBarController = [[UITabBarController alloc] init];
    tabBarController.viewControllers = @[firstNV,secondNV,threeNV,fourNV];
    [[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];
    [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
    LLTabBar *tabBar = [[LLTabBar alloc] initWithFrame:tabBarController.tabBar.bounds];
    tabBar.tabBarItemAttributes = @[@{kLLTabBarItemAttributeTitle : @"首页", kLLTabBarItemAttributeNormalImageName : @"tab-home", kLLTabBarItemAttributeSelectedImageName : @"tab-home-sel", kLLTabBarItemAttributeType : @(LLTabBarItemNormal)},
                                    @{kLLTabBarItemAttributeTitle : @"分类", kLLTabBarItemAttributeNormalImageName : @"tab-product", kLLTabBarItemAttributeSelectedImageName : @"tab-product_sel", kLLTabBarItemAttributeType : @(LLTabBarItemNormal)},
                                    @{kLLTabBarItemAttributeTitle : @"工具", kLLTabBarItemAttributeNormalImageName : @"tab_tool", kLLTabBarItemAttributeSelectedImageName : @"tab_tool_sel", kLLTabBarItemAttributeType : @(LLTabBarItemNormal)},
                                    @{kLLTabBarItemAttributeTitle : @"我", kLLTabBarItemAttributeNormalImageName : @"tab_my", kLLTabBarItemAttributeSelectedImageName : @"tab_my_sel", kLLTabBarItemAttributeType : @(LLTabBarItemNormal)}];
    tabBar.delegate = nil;
    [tabBarController.tabBar addSubview:tabBar];
    [self setWindowForPush:tabBarController];
}

//UI设置
- (void)setUI
{
    //去掉底栏黑线，并用图替换底色
    CGRect rect = CGRectMake(0, 0, UISCREENWEITH, UISCREENHEIGHT);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [ClEARColor CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //    [[UITabBar appearance] setBackgroundColor:[UIColor colorWithRed:254.0/255.0 green:254.0/255.0 blue:254.0/255.0 alpha:1.0]];
    [[UITabBar appearance] setBackgroundImage:LoadImage(@"tabbar-1")];
    [UITabBar appearance].translucent = NO;
    [[UITabBar appearance] setShadowImage:img];
    [[UITabBarItem appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName:KMainColor} forState:UIControlStateSelected];
    //    [[UITabBar appearance] setBackgroundImage:LoadImage(@"tabbar-1")];
    //    [[UINavigationBar appearance]setBackgroundImage:LoadImage(@"top_bg") forBarMetrics:UIBarMetricsDefault];
    //    if (UISCREENHEIGHT >= 812)
    //    {
    //        [[UINavigationBar appearance]setBackgroundImage:LoadImage(@"top_bg-1") forBarMetrics:UIBarMetricsDefault];
    //    }
    [[UINavigationBar appearance] setBarStyle:UIBarStyleDefault];
    [[UINavigationBar appearance] setTranslucent:NO];
    [[UINavigationBar appearance] setShadowImage:[[UIImage alloc]init]];
    //去掉导航栏背景透明度
    [[UINavigationBar appearance] setTranslucent:NO];
    //设置导航栏的背景颜色
//    [[UINavigationBar appearance] setBarTintColor:KMainColor];
    [[UINavigationBar appearance] setTintColor:FFFFFFColor];
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:SetFont(20.0),NSForegroundColorAttributeName:FFFFFFColor}];
    if (IS_iPhone_4S)
    {
        [[UINavigationBar appearance]setBackgroundImage:LoadImage(@"320x64.png") forBarMetrics:UIBarMetricsDefault];
    }
    else if (IS_iPhone_5)
    {
        [[UINavigationBar appearance]setBackgroundImage:LoadImage(@"320x64.png") forBarMetrics:UIBarMetricsDefault];
    }
    else if (IS_iPhone_6)
    {
        [[UINavigationBar appearance]setBackgroundImage:LoadImage(@"375x64.png") forBarMetrics:UIBarMetricsDefault];
    }
    else if (IS_iPhone6_Plus)
    {
        [[UINavigationBar appearance]setBackgroundImage:LoadImage(@"621x88.png") forBarMetrics:UIBarMetricsDefault];
    }
    else if (IS_iPhoneX)
    {
        [[UINavigationBar appearance]setBackgroundImage:LoadImage(@"563x88.png") forBarMetrics:UIBarMetricsDefault];
    }
    else if (IS_iPhoneXs_Max)
    {
        [[UINavigationBar appearance]setBackgroundImage:LoadImage(@"621x88.png") forBarMetrics:UIBarMetricsDefault];
    }
    else if (IS_iPhoneXr)
    {
        [[UINavigationBar appearance]setBackgroundImage:LoadImage(@"414x88.png") forBarMetrics:UIBarMetricsDefault];
    }
    else
    {
        [[UINavigationBar appearance]setBackgroundImage:LoadImage(@"375x64.png") forBarMetrics:UIBarMetricsDefault];
    }
}

//设置导航栏背景图
#define NavigationBarBackgroundImage

- (void)registerShareKey
{
    //第一步：注册key
    [OpenShare connectQQWithAppId:@"1105760537"];
    [OpenShare connectWeixinWithAppId:@"wx8c6826164c3066b6"];
}

//推出视图控制器
- (void)setWindowForPush:(UIViewController*)vc
{
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.window.rootViewController = vc;
    self.window.backgroundColor = FFFFFFColor;
    [self.window makeKeyAndVisible];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    /* 跳转到主界面 */
    [self showTabbar];
    /* 添加启动页广告图延时展示 */
    [self.window addSubview:self.backView];
    /* 设置HUD */
    [self svPreferrenceConf];
    /* 请求服务获取广告图列表 */
    [self postGetImages];
    /* 注册分享key */
    [self registerShareKey];
    /* 设置UI */
    [self setUI];
    /* 友盟推送相关设置 */
    [self setYOUMengActionWithLaunchOptions:launchOptions];
    /* 友盟统计 */
    [self addYouMengSDK];
//    BOOL wechat = [[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"weixin://"]];
//    if (wechat)
//    {
//        NSLog(@"%@",@"可以打开微信，已经安装");
//    }
//    else
//    {
//        NSLog(@"%@",@"不可以打开微信，没有安装");
//    }
    return YES;
}

//iOS10新增：处理前台收到通知的代理方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [UMessage setAutoAlert:NO];
        //应用处于前台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:[NSString stringWithFormat:@"%@",userInfo] forKey:@"userInfoNotification"];
    }else{
        //应用处于前台时的本地推送接受
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler
{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:[NSString stringWithFormat:@"%@",userInfo] forKey:@"userInfoNotification"];
    }else{
        //应用处于后台时的本地推送接受
    }
}

//友盟推送相关设置
- (void)setYOUMengActionWithLaunchOptions:(NSDictionary *)launchOptions
{
    /*
     **********************
     **********************
     **********************
     ***设置友盟推送AppKey****
     **********************
     **********************
     **********************
     */
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    [UMessage startWithAppkey:ZHENGSHI launchOptions:launchOptions];
    //注册通知
    [UMessage registerForRemoteNotifications];
    //iOS10必须加下面这段代码。
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    UNAuthorizationOptions types10=UNAuthorizationOptionBadge|UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10 completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted)
        {
            //点击允许
        } else
        {
            //点击不允许
        }
    }];
    //如果你期望使用交互式(只有iOS 8.0及以上有)的通知，请参考下面注释部分的初始化代码
    UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
    action1.identifier = @"action1_identifier";
    action1.title=@"打开应用";
    action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
    UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
    action2.identifier = @"action2_identifier";
    action2.title=@"忽略";
    action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
    action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
    action2.destructive = YES;
    UIMutableUserNotificationCategory *actionCategory1 = [[UIMutableUserNotificationCategory alloc] init];
    actionCategory1.identifier = @"category1";//这组动作的唯一标示
    [actionCategory1 setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
    NSSet *categories = [NSSet setWithObjects:actionCategory1, nil];
    
    //如果要在iOS10显示交互式的通知，必须注意实现以下代码
    if ([[[UIDevice currentDevice] systemVersion]intValue]>=10) {
        UNNotificationAction *action1_ios10 = [UNNotificationAction actionWithIdentifier:@"action1_ios10_identifier" title:@"打开应用" options:UNNotificationActionOptionForeground];
        UNNotificationAction *action2_ios10 = [UNNotificationAction actionWithIdentifier:@"action2_ios10_identifier" title:@"忽略" options:UNNotificationActionOptionForeground];
        //UNNotificationCategoryOptionNone
        //UNNotificationCategoryOptionCustomDismissAction  清除通知被触发会走通知的代理方法
        //UNNotificationCategoryOptionAllowInCarPlay       适用于行车模式
        UNNotificationCategory *category1_ios10 = [UNNotificationCategory categoryWithIdentifier:@"category101" actions:@[action1_ios10,action2_ios10]   intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
        NSSet *categories_ios10 = [NSSet setWithObjects:category1_ios10, nil];
        [center setNotificationCategories:categories_ios10];
    }
    else
    {
        [UMessage registerForRemoteNotifications:categories];
    }
    //如果对角标，文字和声音的取舍，请用下面的方法
    UIRemoteNotificationType types7 = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
    UIUserNotificationType types8 = UIUserNotificationTypeAlert|UIUserNotificationTypeSound|UIUserNotificationTypeBadge;
    [UMessage registerForRemoteNotifications:categories withTypesForIos7:types7 withTypesForIos8:types8];
    //打开日志，方便调试
    [UMessage setLogEnabled:YES];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    //1.2.7版本开始不需要用户再手动注册devicetoken，SDK会自动注册
    // [UMessage registerDeviceToken:deviceToken];
    NSLog(@"%@",deviceToken);
    //下面这句代码只是在demo中，供页面传值使用。
    [self postTestParams:[self stringDevicetoken:deviceToken] idfa:[self idfa] openudid:[self openUDID]];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    self.userInfo = userInfo;
    //    self.userInfo = userInfo;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"userInfoNotification" object:self userInfo:userInfo];
    //关闭友盟自带的弹出框
    [UMessage setAutoAlert:NO];
    [UMessage didReceiveRemoteNotification:userInfo];
}

//获取当前控制器
- (UIViewController *)currentViewController1
{
    UIWindow *keyWindow  = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = keyWindow.rootViewController;
    if ([vc isKindOfClass:[UINavigationController class]])
    {
        vc = [(UINavigationController *)vc visibleViewController];
    }
    else if ([vc isKindOfClass:[UITabBarController class]])
    {
        vc = [(UITabBarController *)vc selectedViewController];
    }
    return vc;
}

////获取当前控制器
//- (UIViewController *)currentViewController
//{
//    UIWindow *keyWindow  = [UIApplication sharedApplication].keyWindow;
//    UIViewController *vc = keyWindow.rootViewController;
//    while (vc.presentedViewController)
//    {
//        vc = vc.presentedViewController;
//        if ([vc isKindOfClass:[UINavigationController class]])
//        {
//            vc = [(UINavigationController *)vc visibleViewController];
//        }
//        else if ([vc isKindOfClass:[UITabBarController class]])
//        {
//            vc = [(UITabBarController *)vc selectedViewController];
//        }
//    }
//    return vc;
//}

//调取用户联系目录授权验证
//- (void)judgeUserAdressStatus
//{
//    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
//    if ( status == CNAuthorizationStatusAuthorized)
//    {
//        //如果已经授权，直接返回
//        return;
//    }
//    else
//    {
//        //iOS9授权
//        CNContactStore *store = [[CNContactStore alloc] init];
//        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error)
//        {
//            if (error)
//            {
//                NSLog(@"error=%@",error);
//            }
//            if (granted)
//            {
//                NSLog(@"授权成功");
//            }else
//            {
//                NSLog(@"授权失败");
//            }
//        }];
//    }
//}

//配置友盟
- (void)addYouMengSDK
{
    /*
     *
     *
     *  设置友盟推送 AppKey。
     *
     *
     */
    UMConfigInstance.appKey = ZHENGSHI;
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
}

//触发时机：程序进入前台并处于活动状态时调用。
//适宜操作：这个阶段应该恢复UI状态（例如游戏状态）
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    
}

//当app回到前台运行时
- (void)applicationWillEnterForeground:(UIApplication *)application
{
//    [application setApplicationIconBadgeNumber:0];
//    [application cancelAllLocalNotifications];
}

//当app进入后台的时候
- (void)applicationDidEnterBackground:(UIApplication *)application
{
//    [MobClick setBackgroundTaskEnabled:YES];
//    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

//iOS10以前接收的方法
/*
-(void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler
{
    //这个方法用来做action点击的统计
    [UMessage sendClickReportForRemoteNotification:userInfo];
    //下面写identifier对各个交互式的按钮进行业务处理
}
*/

//- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo
//{
//    self.userInfo = userInfo;
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"userInfoNotification" object:self userInfo:userInfo];
//    //关闭友盟自带的弹出框
//    [UMessage setAutoAlert:NO];
//    [UMessage didReceiveRemoteNotification:userInfo];
//    if (userInfo)
//    {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self dealWithMyMessagePush:userInfo];
//        });
//    }
//}

- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)err
{
    NSString *error_str = [NSString stringWithFormat: @"%@", err];
    NSLog(@"Failed to get token, error:%@", error_str);
}

#pragma mark 以下的
-(NSString *)stringDevicetoken:(NSData *)deviceToken
{
    NSString *token = [deviceToken description];
    NSString *pushToken = [[[token stringByReplacingOccurrencesOfString:@"<"withString:@""]                   stringByReplacingOccurrencesOfString:@">"withString:@""] stringByReplacingOccurrencesOfString:@" "withString:@""];
    return pushToken;
}

-(NSString *)idfa
{
    return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
}

-(NSString *)openUDID
{
    NSString* openUdid = nil;
    if (openUdid==nil) {
        CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
        CFStringRef cfstring = CFUUIDCreateString(kCFAllocatorDefault, uuid);
        const char *cStr = CFStringGetCStringPtr(cfstring,CFStringGetFastestEncoding(cfstring));
        unsigned char result[16];
        CC_MD5( cStr,(CC_LONG)strlen(cStr), result );
        CFRelease(uuid);
        CFRelease(cfstring);
        openUdid = [NSString stringWithFormat:
                    @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%08lx",
                    result[0], result[1], result[2], result[3],
                    result[4], result[5], result[6], result[7],
                    result[8], result[9], result[10], result[11],
                    result[12], result[13], result[14], result[15],
                    (unsigned long)(arc4random() % NSUIntegerMax)];
    }
    return openUdid;
}

-(void)postTestParams:(NSString *)devicetoken idfa:(NSString *)idfa  openudid:(NSString *)openudid
{
    UIUserNotificationType types;
    UIRemoteNotificationType setting ;
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
#endif
    if ([[[UIDevice currentDevice] systemVersion]intValue]<8) {// system <iOS8
        setting = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        NSLog(@"%lu",(unsigned long)setting);
        [ud setObject:[NSString stringWithFormat:@"%lu",(setting & UIRemoteNotificationTypeAlert)] forKey:@"UMPAlert"];
        [ud setObject:[NSString stringWithFormat:@"%lu",(setting & UIRemoteNotificationTypeSound)] forKey:@"UMPSound"];
        [ud setObject:[NSString stringWithFormat:@"%lu",(setting & UIRemoteNotificationTypeBadge)] forKey:@"UMPBadge"];
    }else if ([[[UIDevice currentDevice] systemVersion]intValue]>=10)
    {// system >=iOS10
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            [ud setObject:[NSString stringWithFormat:@"%ld",(long)settings.alertSetting] forKey:@"UMPAlert"];
            [ud setObject:[NSString stringWithFormat:@"%ld",(long)settings.soundSetting] forKey:@"UMPSound"];
            [ud setObject:[NSString stringWithFormat:@"%ld",(long)settings.badgeSetting] forKey:@"UMPBadge"];
        }];
#endif
    }else{
        types = [[UIApplication sharedApplication] currentUserNotificationSettings].types;
        [ud setObject:[NSString stringWithFormat:@"%lu",(types & UIRemoteNotificationTypeAlert)] forKey:@"UMPAlert"];
        [ud setObject:[NSString stringWithFormat:@"%lu",(types & UIRemoteNotificationTypeSound)] forKey:@"UMPSound"];
        [ud setObject:[NSString stringWithFormat:@"%lu",(types & UIRemoteNotificationTypeBadge)] forKey:@"UMPBadge"];
    }
    [ud setObject:devicetoken forKey:@"UMPDevicetoken"];
    [ud setObject:idfa forKey:@"UMPIdfa"];
    [ud setObject:openudid forKey:@"UMPOpenudid"];
    
}

@end
